package com.jinhu.Service;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpException;
import com.jinhu.Entity.orderRecord;
import net.hasor.dbvisitor.jdbc.core.JdbcTemplate;
import net.hasor.dbvisitor.lambda.LambdaTemplate;
import net.hasor.dbvisitor.solon.Db;
import org.noear.solon.annotation.Component;

import java.sql.SQLException;
import java.util.List;

@Component
public class OrderServiceImpl implements IOrderService{

    @Db
    LambdaTemplate lambdaTemplate;
    @Db
    JdbcTemplate jdbcTemplate;

    @Override
    public List<orderRecord> getOrderByDate(String userid,String date){
        try {
            String format = "";
            if(date.length()==10){
                 format = StrUtil.format("select * from orderRecord where userid = {} and DATE(time) = '{}'", userid, date);
            }else if(date.length()==19){
                String startTime = date.substring(0, 14)+"00:00";
                String stopTime = date.substring(0, 14)+"59:59";
                format = StrUtil.format("SELECT * FROM orderRecord WHERE userid = {} and DATE(time) BETWEEN '{}' AND '{}'", userid, startTime,stopTime);
            }else {
                throw new HttpException("时间格式传入错误");
            }
            List<orderRecord> orderRecords = jdbcTemplate.queryForList(format, orderRecord.class);
            return orderRecords;
        } catch (SQLException e) {
            throw new RuntimeException("查询数据失败"+e);
        }
    }

    @Override
    public orderRecord insertOrder(orderRecord order){
        try {

            int i = lambdaTemplate.lambdaInsert(orderRecord.class)
                    .applyEntity(order)
                    .executeSumResult();
            if(i>0){
                return order;
            }else {
                return null;
            }
        } catch (SQLException e) {
            throw new RuntimeException("插入数据失败"+e);

        }
    }

    @Override
    public orderRecord updateOder(orderRecord order){
        try {
            int i = lambdaTemplate.lambdaUpdate(orderRecord.class)
                    .eq(orderRecord::getId,order.getId())
                    .updateToSample(order)
                    .doUpdate();
            if(i>0){
                return order;
            }else {
                return null;
            }
        } catch (SQLException e) {
            throw new RuntimeException("修改数据失败"+e);
        }

    }
}
